package com.medical.literature.document.service.impl;

import com.medical.literature.common.exception.BusinessException;
import com.medical.literature.document.service.FileStorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 本地文件存储服务实现
 */
@Service
public class LocalFileStorageServiceImpl implements FileStorageService {
    
    // 手动添加log变量
    private static final Logger log = LoggerFactory.getLogger(LocalFileStorageServiceImpl.class);
    
    @Value("${file.upload.path:D:/upload/literature/}")
    private String uploadPath;
    
    // 确保路径使用正确的文件分隔符
    @PostConstruct
    public void init() {
        if (uploadPath != null) {
            uploadPath = uploadPath.replace("\\", "/").replaceAll("/+$", "");
        }
    }
    
    @Value("${file.max.size:52428800}") // 50MB
    private long maxFileSize;

    @Override
    public String storeFile(MultipartFile file, Long userId) {
        // 验证文件
        validateFile(file);
        
        try {
            // 创建存储目录
            String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            String dirPath = uploadPath + "/" + datePath + "/" + userId;
            // 确保路径使用正确的文件分隔符
            dirPath = dirPath.replace("/", File.separator);
            Path uploadDir = Paths.get(dirPath);
            Files.createDirectories(uploadDir);
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = StringUtils.getFilenameExtension(originalFilename);
            String newFilename = UUID.randomUUID().toString() + "." + fileExtension;
            
            // 存储文件
            Path filePath = uploadDir.resolve(newFilename);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
            
            // 返回相对路径，使用正斜杠以便于跨平台兼容
            String relativePath = datePath + "/" + userId + "/" + newFilename;
            log.info("文件存储成功: {}", relativePath);
            return relativePath;
            
        } catch (IOException e) {
            log.error("文件存储失败: {}", e.getMessage(), e);
            throw new BusinessException("文件存储失败");
        }
    }

    @Override
    public byte[] getFile(String filePath) {
        try {
            // 构造完整文件路径，确保跨平台兼容性
            String normalizedPath = Paths.get(uploadPath, filePath).toString();
            Path path = Paths.get(normalizedPath);
            if (!Files.exists(path)) {
                throw new BusinessException("文件不存在");
            }
            return Files.readAllBytes(path);
        } catch (IOException e) {
            log.error("文件读取失败: {}", e.getMessage(), e);
            throw new BusinessException("文件读取失败");
        }
    }

    @Override
    public boolean fileExists(String filePath) {
        // 构造完整文件路径，确保跨平台兼容性
        String normalizedPath = Paths.get(uploadPath, filePath).toString();
        Path path = Paths.get(normalizedPath);
        return Files.exists(path);
    }
    
    @Override
    public void deleteFile(String filePath) {
        try {
            // 构造完整文件路径，确保跨平台兼容性
            String normalizedPath = Paths.get(uploadPath, filePath).toString();
            Path path = Paths.get(normalizedPath);
            Files.deleteIfExists(path);
            log.info("文件删除成功: {}", filePath);
        } catch (IOException e) {
            log.error("文件删除失败: {}", e.getMessage(), e);
            throw new BusinessException("文件删除失败");
        }
    }
    
    /**
     * 验证上传文件
     */
    private void validateFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new BusinessException("文件不能为空");
        }
        
        if (file.getSize() > maxFileSize) {
            throw new BusinessException("文件大小不能超过50MB");
        }
        
        String originalFilename = file.getOriginalFilename();
        if (!StringUtils.hasText(originalFilename)) {
            throw new BusinessException("文件名不能为空");
        }
        
        String fileExtension = StringUtils.getFilenameExtension(originalFilename);
        if (!isValidFileType(fileExtension)) {
            throw new BusinessException("不支持的文件类型，仅支持PDF、DOC、DOCX、TXT等格式");
        }
    }
    
    /**
     * 检查文件类型是否有效
     */
    private boolean isValidFileType(String extension) {
        if (!StringUtils.hasText(extension)) {
            return false;
        }
        
        String ext = extension.toLowerCase();
        // 支持更多文件类型，包括图片类型
        return ext.equals("pdf") || ext.equals("doc") || ext.equals("docx") || 
               ext.equals("txt") || ext.equals("rtf") || ext.equals("jpg") ||
               ext.equals("jpeg") || ext.equals("png") || ext.equals("bmp") ||
               ext.equals("gif");
    }
}